﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;
using Mes.采购管理.model;
using Mes;
using System.Net.Http;



namespace Mes.采购管理
{
    public partial class Purchase : Form
    {
        // 在Purchase类内部添加原料列表
        private List<Material> materials = new List<Material>();
        public Purchase()
        {
            InitializeComponent();
            dateRequest_Ddte.Value = DateTime.Today;
            // 表单加载时生成采购单号
            textReqest_No.Text = GeneratePurchaseNo();
        }

        private async void buttonSaved_Click(object sender, EventArgs e)
        {
            // 自动生成采购单号
            string purchaseNo = GeneratePurchaseNo();
            textReqest_No.Text = purchaseNo;

            // 自动生成批次号
            string batchNo = GenerateBatchNo();
            textBatch_No.Text = batchNo;

            int approverId = comApprover_id.SelectedIndex + 1;

            if (approverId <= 0)
            {
                ShowError("请选择一个有效的审批人。");
                return;
            }

            if (comMatelal_name.SelectedIndex < 0)
            {
                ShowError("请选择原料");
                comMatelal_name.Focus();
                return;
            }

            if (numerRequest_Qty.Value <= 0)
            {
                ShowError("申请数量必须大于0");
                numerRequest_Qty.Focus();
                return;
            }

            var purchase = new
            {
                Reqest_No = textReqest_No.Text,
                Materlal_Id = textMaterlal_Id.Text,
                Matelal_name = comMatelal_name.Text,
                Request_Qty = numerRequest_Qty.Value,
                Matelal_Spec = comMatelal_Spec.Text,
                // 修复：提取数字并转换为整数
                Matelal_Dimension = int.Parse(comMatelal_Dimension.Text.Replace("mm", "")),
                Request_Ddte = dateRequest_Ddte.Value.ToString("o"),
                Budget_Amount = textBudget_Amount.Text,
                Batch_No = batchNo,  // 使用生成的批次号
                Approver_id = approverId,  // 使用整数类型
                command = "AddMaterial"
            };

            try
            {
                string json = JsonConvert.SerializeObject(purchase);
                string apiUrl = "http://10.223.8.9:8082/api/Purchase/AddMaterial";
                
                using (HttpClient client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "utf-8");
                    client.Timeout = TimeSpan.FromSeconds(10);
                    
                    // 添加Token认证头
                    if (!string.IsNullOrEmpty(login.CurrentToken))
                    {
                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    }
            
                    // 创建请求内容
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    
                    // 发送POST请求
                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);
                    string responseText = await response.Content.ReadAsStringAsync();
                    
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("采购申请添加成功！");
                        // 清空表单
                        ClearForm();
                    
                        // 刷新采购列表页面
                        bool isRefreshed = false;
                        foreach (Form form in Application.OpenForms)
                        {
                            if (form is Purchaseshow purchaseshowForm)
                            {
                                purchaseshowForm.RefreshData();
                                isRefreshed = true;
                                break;
                            }
                        }
                    
                        if (!isRefreshed)
                        {
                            MessageBox.Show("采购申请添加成功，但未找到采购列表页面。");
                        }
                    
                        // 关闭当前添加页面
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show($"添加失败，HTTP 状态码：{(int)response.StatusCode}, 错误信息：{responseText}");
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                string errorText = "未知错误";
                int statusCode = 0;
                string errorType = "网络请求错误";
                
                if (ex.Message.Contains("40"))
                {
                    errorType = "客户端错误";
                }
                else if (ex.Message.Contains("50"))
                {
                    errorType = "服务器错误";
                }
                else if (ex.Message.Contains("Connect"))
                {
                    errorType = "连接失败";
                    errorText = "无法连接到服务器，请检查网络连接或服务器状态。";
                }
                else if (ex.Message.Contains("timeout"))
                {
                    errorType = "请求超时";
                    errorText = "请求超时，请稍后再试。";
                }
                
                ShowError($"添加失败：{errorType}\n错误信息：{ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误：{ex.Message}");
            }
        }

        // 生成采购单号的方法
        private string GeneratePurchaseNo()
        {
            string prefix = "PO";
            string datePart = DateTime.Now.ToString("yyyyMMdd");
            // 结合时间戳和随机数增强唯一性
            string timestamp = DateTime.Now.ToString("HHmmss");
            Random random = new Random();
            string randomPart = random.Next(1000, 9999).ToString();
            return prefix + datePart + timestamp + randomPart;
        }

        // 添加生成批次号的方法
        private string GenerateBatchNo()
        {
            string prefix = "BAT";
            string datePart = DateTime.Now.ToString("yyyyMMdd");
            Random random = new Random();
            string randomPart = random.Next(10000000, 99999999).ToString();
            return prefix + datePart + randomPart;
        }

        // 清空表单方法
        private void ClearForm()
        {
            textReqest_No.Text = "";
            textMaterlal_Id.Text = "";
            comMatelal_name.Text = "";
            numerRequest_Qty.Value = 0;
            comMatelal_Spec.Text = "";
            comMatelal_Dimension.Text = "";
            dateRequest_Ddte.Value = DateTime.Today;
            textBudget_Amount.Text = "";
            textBatch_No.Text = "";
            comApprover_id.SelectedIndex = -1;
            comMatelal_name.SelectedIndex = -1; // 重置原料下拉框
        }

        // 按钮悬停效果
        private void button_MouseEnter(object sender, EventArgs e)
        {
            Button button = sender as Button;
            if (button != null)
            {
                int r = Math.Max(0, button.BackColor.R - 20);
                int g = Math.Max(0, button.BackColor.G - 20);
                int b = Math.Max(0, button.BackColor.B - 20);
                button.BackColor = Color.FromArgb(r, g, b);
                button.Font = new Font(button.Font, FontStyle.Bold);
            }
        }

        // 按钮离开效果
        private void button_MouseLeave(object sender, EventArgs e)
        {
            Button button = sender as Button;
            if (button != null)
            {
                if (button.Name == "button1")
                {
                    button.BackColor = Color.FromArgb(0, 128, 255);
                }
                else
                {
                    button.BackColor = Color.Gainsboro;
                }
                button.Font = new Font(button.Font, FontStyle.Regular);
            }
        }

        private void Purchase_Load(object sender, EventArgs e)
        {
            // 初始化审批人下拉框
            List<string> 审批人 = new List<string>()
            {
                "张三", "王五", "李四"
            };
            comApprover_id.DataSource = 审批人;
            comApprover_id.SelectedIndex = -1;
            List<string> 规格型号 = new List<string>()
            {
                "次等豆","中等豆", "上等豆", "特等豆"
            };
            comMatelal_Spec.DataSource = 规格型号;
            comMatelal_Spec.SelectedIndex = -1;
            
            List<string> 尺寸 = new List<string>()
            {
                "4mm", "6mm", "8mm"
            };
            comMatelal_Dimension.DataSource = 尺寸;
            comMatelal_Dimension.SelectedIndex = -1;

            // 初始化原料数据
            materials = new List<Material>()
            {
                new Material { Id = "MAT001", Name = "黄豆" },
                new Material { Id = "MAT002", Name = "绿豆" },
                new Material { Id = "MAT003", Name = "红豆" },
                new Material { Id = "MAT004", Name = "黑豆" }
                // 可以根据实际需求添加更多原料
            };
        
            // 绑定原料下拉框
            comMatelal_name.DataSource = materials;
            comMatelal_name.DisplayMember = "Name";  // 显示名称
            comMatelal_name.ValueMember = "Id";      // 值成员
            comMatelal_name.SelectedIndex = -1;
        
            // 添加选择事件处理
            comMatelal_name.SelectedIndexChanged += ComMatelal_name_SelectedIndexChanged;
        }
        private void ComMatelal_name_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comMatelal_name.SelectedIndex >= 0)
            {
                // 获取选中的原料
                Material selectedMaterial = (Material)comMatelal_name.SelectedItem;
                // 反填原料编号和名称
                textMaterlal_Id.Text = selectedMaterial.Id;
                comMatelal_name.Text = selectedMaterial.Name;
            }
            else
            {
                // 清空输入
                textMaterlal_Id.Text = "";
                comMatelal_name.Text = "";
            }
        }

        // 添加统一的错误提示方法
        private void ShowError(string message)
        {
            MessageBox.Show(message, "操作错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

